/*
 * @Author: 贺楚 2402041262@qq.com
 * @Date: 2023-01-11 17:35:48
 * @LastEditors: 贺楚 2402041262@qq.com
 * @LastEditTime: 2023-01-14 15:24:18
 * @FilePath: \vue-admin-template-master\src\permission.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import router from './router'
import store from './store'
import {
  Message
} from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import {
  getToken
} from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'


import { resetRouter, constantRoutes } from '@/router'

// 两个路由数组进行对比，对比显示当前用户该显示的路由权限
const computedAsyncRouters = (constantRoutes, routers) => {

  let newArr = routers.map(item => {
    return item.componentName;
  })

  return constantRoutes.filter(item => {
    if (newArr.indexOf(item.name) != -1) {
      if (item.children && item.children.length) {
        item.children = computedAsyncRouters(item.children, routers)
      }
      return true;
    }
  })
}

NProgress.configure({
  showSpinner: false
}) // NProgress Configuration

const whiteList = ['/login', '/404'] // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()
  const hasGetUserRole = localStorage.getItem('adv_session_token')
  // console.log('hasToken', hasToken)
  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({
        path: '/'
      })
      NProgress.done()
    } else {

      const hasGetUserInfo = store.getters.name
      console.log('hasGetUserInfo', hasGetUserInfo);
      // console.log('qqqzdsd', hasGetUserRole, hasGetUserInfo)
      // if(hasGetUserRole == '广告代理商'){
      //   next()
      //   return;
      // }
      if (hasGetUserInfo && (to.meta.noAuth || store.getters.permissionList.some(i => i.componentName === to.name))) {
        // await store.dispatch('user/getInfo')
        next()
      } else {
        try {
          // get user info
          if (hasGetUserRole) {
            // console.log('广告代理')
            let permissionList = JSON.parse(localStorage.getItem('permissionArr'))
            // console.log('权限路由',permissionList)
            let treesId = permissionList.map(item => {
              return item.componentName;
            })
            let userRole = '广告代理商'
            await store.commit('user/SET_TOKEN', hasGetUserRole)
            await store.commit('user/SET_NAME', localStorage.getItem('adv_userName'))
            await store.commit('user/SET_USERROLE', userRole)
            await store.commit('user/SET_PERMISSIONLIST', permissionList)
            await store.commit('user/SET_TREESID', treesId)
            await store.commit('user/SET_RESULTASYNCROUTER', computedAsyncRouters(constantRoutes,
              permissionList))
          } else {
            await store.dispatch('user/getInfo')
          }
          console.log(store.getters.permissionList.at(0).componentName)

          if (to.meta.noAuth || store.getters.permissionList.some(i => i.componentName === to.name)) {
            next()

          } else {
            next(store.state.user.resultAsyncRouter.at(0).path)
          }
          NProgress.done()
        } catch (error) {
          // remove token and go to login page to re-login
          if (!hasGetUserRole) {
            await store.dispatch('user/resetToken')
            Message.error(error || 'Has Error')
            next(`/login?redirect=${to.path}`)
            NProgress.done()
          } else {
            // localStorage.removeItem('adv_session_token')
            // Message.error(error || 'Has Error')
            next(`/login?adv=1`)
            // NProgress.done()
          }

        }
      }
    }
  } else {
    /* has no token*/

    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      if (hasGetUserRole) {
        next(`/login?adv=1`)
      } else {
        next(`/login?redirect=${to.path}`)
      }
      // next()
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
